//
//  NewHomeViewController.m
//  quxiangtao
//
//  Created by E人一铺 on 2019/2/20.
//  Copyright © 2019年 shanhaijin. All rights reserved.
//

#import "NewHomeViewController.h"
#import "NewHomeCollectionViewCell.h"
#import "NewHomeHeadView.h"
//#import "NewHomeModel.h"

//#import "SegmentView.h"
//#import "QNetWorkRequest.h"
#import "HSUpdateApp.h"
//#import "HomeCollectionView.h"

#import "TbGoodsListModel.h"
#import "TbCategoryTitleModel.h"
#import "BottomGoodsCollectionViewCell.h"
#import "PopupWebView.h"
#import <AudioToolbox/AudioToolbox.h>
#import "ShopDetailController.h"
static NSString *bottomGoodsCellID = @"bottomGoodsCellID";

@interface NewHomeViewController ()<UICollectionViewDelegate, UICollectionViewDataSource>
{
    SystemSoundID scoreClickBtnID;   // 自己设置的音效 (系统的振动音效 - kSystemSoundID_Vibrate)
}
@property (nonatomic,strong) UICollectionView *collectionView;
@property (nonatomic,strong) NewHomeHeadView *backView;
@property (nonatomic,strong) NSMutableArray *dataArray;
@property (nonatomic,assign) NSInteger page;

@property (nonatomic , copy)NSString *clsaaId;
@property (nonatomic, strong) PopupWebView *popopview;

@end

@implementation NewHomeViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    self.page = 1;
    
    self.view.backgroundColor = [UIColor colorWithHexString:@"EFEFEF"];
    
    if (@available(iOS 11.0, *)) {
        [[UIScrollView appearance] setContentInsetAdjustmentBehavior:UIScrollViewContentInsetAdjustmentNever];
        self.collectionView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    }else {
        self.automaticallyAdjustsScrollViewInsets = NO;
    }

    [self prepareUI];
    
    MJRefreshNormalHeader*header=[MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(loadNewData)];
    [header beginRefreshing];
    [header setTitle:@"刷新完成!" forState:MJRefreshStateIdle];
    [header setTitle:@"下拉刷新!" forState:MJRefreshStatePulling];
    [header setTitle:@"正在加载..." forState:MJRefreshStateRefreshing];
    header.stateLabel.font= Font(34);
    header.stateLabel.textColor=LightGrayColor;
    header.lastUpdatedTimeLabel.hidden = YES;
    self.collectionView.mj_header = header;

//    chu  更新
    [self uploadVersion];
}

- (void)uploadVersion {
    [HSUpdateApp hs_updateWithAPPID:@"1453275811" withBundleId:nil block:^(NSString *currentVersion, NSString *storeVersion, NSString *openUrl, BOOL isUpdate) {
        if (isUpdate) {
            [self showAlertViewTitle:@"版本检测" subTitle:[NSString stringWithFormat:@"检测到新版本%@,请您更新",storeVersion] openUrl:openUrl];
        }else{
            NSLog(@"当前版本%@,商店版本%@，不需要更新",currentVersion,storeVersion);
        }
    }];
}

-(void)showAlertViewTitle:(NSString *)title subTitle:(NSString *)subTitle openUrl:(NSString *)openUrl{
    UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:title message:subTitle preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *sure = [UIAlertAction actionWithTitle:@"更新" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
        if([[UIDevice currentDevice].systemVersion floatValue] >= 10.0){
            if ([[UIApplication sharedApplication] respondsToSelector:@selector(openURL:options:completionHandler:)]) {
                if (@available(iOS 10.0, *)) {
                    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:openUrl] options:@{} completionHandler:^(BOOL success) {
                    }];
                } else {
                }
            } else {
                [[UIApplication sharedApplication] openURL:[NSURL URLWithString:openUrl]];
            }
        } else{
            bool can = [[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:openUrl]];
            if(can){
                [[UIApplication sharedApplication] openURL:[NSURL URLWithString:openUrl]];
            }
        }
    }];
    [alertVC addAction:sure];
    [self presentViewController:alertVC animated:YES completion:nil];
}

#pragma mark 下拉刷新数据
- (void)loadNewData
{
    [self.collectionView.mj_footer resetNoMoreData];
    self.page = 1;
    [self loadData];
//    [self.collectionView reloadData];
    
    
    
}

- (void)loadMoreData
{
    
    self.page ++;
    [self loadGoodListsData];
    // 刷新表格
    [self.collectionView reloadData];

    // 拿到当前的上拉刷新控件，结束刷新状态
    [self.collectionView.mj_footer endRefreshing];
    
}


- (void)loadData {
    WS(weakSelf)
    NSString *url = @"goods/index/goodsClass";
    [TbCategoryTitleModel getCategoryTitleWithUrl:url successBlock:^(id responseObject) {
        if ([responseObject[@"code"] integerValue] == 1) {
            
            NSArray *arr = responseObject[@"data"];
            TbCategoryTitleModel *model = arr[0];
            weakSelf.clsaaId = model.classid;
            
            [self loadGoodListsData];
            /*
            weakSelf.classID = model.classid;
            weakSelf.oldIndex = 0;
            weakSelf.classArr = arr;
            [weakSelf.segmentPagerVC updateData];
            [weakSelf setupSubViews];
            [weakSelf.v changeModel:model selectButtonIndex:weakSelf.selectIndex];
             */
        }else {
            [[KYAlertView sharedInstance] showAlertViewWithMessage:responseObject[@"msg"]];
        }
    } failBlock:^(NSError *error) {
        if (error) {
            //                [[KYAlertView sharedInstance] showAlertViewWithMessage:Tip];
        }
    }];
    
    /*
    WS(weakSelf)
    [NewHomeModel getDataWithPage:self.page SuccessBlock:^(id responseObject) {
        
        if ([responseObject[@"code"] integerValue] == 1) {
            
                NSArray *arr = responseObject[@"data"];
                if (arr.count > 0 || weakSelf.dataArray.count > 0 ) {
                    
                    if (self.page == 1) {
                        weakSelf.dataArray = (NSMutableArray *)arr;
                    }else {
                        [weakSelf.dataArray addObjectsFromArray:arr];
                    }
                    
                    
                    [weakSelf.collectionView reloadData];
                    if (self.page > 1 && arr.count == 0) {
                        
                        [self.collectionView.mj_footer endRefreshingWithNoMoreData];
                        
                    }
                    

                    [self.collectionView reloadData];
                    
                }else {
                    
                }
  
            
        }else {
            
            [[KYAlertView sharedInstance] showAlertViewWithMessage:responseObject[@"msg"]];
        }
    } failBlock:^(NSError *error) {
        
    }];
    */
}

-(void)loadGoodListsData{
    
    WS(weakSelf)
    [TbGoodsListModel goodsListWithUrl:@"goods/index/goodsList" andPage:self.page withClassID:self.clsaaId successBlock:^(id responseObject) {
        
        if ([responseObject[@"code"] integerValue] == 1) {
            dispatch_async(dispatch_get_global_queue(0, 0), ^{
                NSArray *arr = responseObject[@"data"];
                if (arr.count > 0 || weakSelf.dataArray.count > 0 ) {
                    if (weakSelf.page == 1) {
                        [weakSelf.dataArray removeAllObjects];
                        [weakSelf.dataArray addObjectsFromArray:arr];
                    }else {
                        [weakSelf.dataArray addObjectsFromArray:arr];
                    }
                    CGFloat height = 0;
                    int num = (int)weakSelf.dataArray.count / 2;
                    if (weakSelf.dataArray.count % 2 == 0) {
                        height = num * jisuan(525) + jisuan(170);
                    }else {
                        height = (num + 1) * jisuan(525) + jisuan(170);
                    }
                    
                }else {
                    
                }
                [self.collectionView reloadData];
                // 拿到当前的下拉刷新控件，结束刷新状态
                [self.collectionView.mj_header endRefreshing];
//                dispatch_async(dispatch_get_main_queue(), ^{
//                    if (weakSelf.selectButtonIndex != 4) {
//                        [UIView performWithoutAnimation:^{
//                            [weakSelf.goodsCollectionView reloadData];
//                        }];
//                    }
//                });
                
            });
            
        }else {
            
            [[KYAlertView sharedInstance] showAlertViewWithMessage:responseObject[@"msg"]];
        }
        
    } failBlock:^(NSError *error) {
        
        if (error) {
            //                [[KYAlertView sharedInstance] showAlertViewWithMessage:Tip];
        }
        
    }];
    
    
}

#pragma mark - UICollectionViewDelegate
- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath{
    
    UICollectionReusableView *reusableview = nil;
    
    if (kind == UICollectionElementKindSectionHeader){
        
        UICollectionReusableView *header = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"NewHomeViewControllerHeadID" forIndexPath:indexPath];
        
        header.backgroundColor = [UIColor colorWithHexString:@"ECEFF3"];
        [header addSubview:self.backView];
        self.backView.backgroundColor = [UIColor clearColor];
        self.backView.frame = header.bounds;
        self.backView.parentVc = self;
        reusableview = header;
        
    }
    return reusableview;
    
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    BottomGoodsCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:bottomGoodsCellID forIndexPath:indexPath];
    cell.backgroundColor = WhiteColor;
    cell.layer.cornerRadius = jisuan(10);
    cell.layer.masksToBounds = YES;
    cell.model = self.dataArray[indexPath.item];
    return cell;
    /*
    NewHomeCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"NewHomeCollectionViewCell" forIndexPath:indexPath];
    cell.parentVc = self;
    //砍价model
    NewHomeModel *model = self.dataArray[indexPath.row];
    cell.model = model;
    return cell;
    */
    
    
}
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
    return 1;
}
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    return self.dataArray.count;
    
}

- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout insetForSectionAtIndex:(NSInteger)section {
    return UIEdgeInsetsMake(jisuan(8), jisuan(20), jisuan(8), jisuan(20));
}
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    //趣豆功能
//    static BOOL shouldPrevent;
//    if (shouldPrevent) return;
//    shouldPrevent = YES;
//    self.popopview = [[PopupWebView alloc] init];
//    self.popopview.hidden = YES;
//    self.popopview.frame = CGRectMake(0, 0, WIDTH, HEIGHT);
//    [[UIApplication sharedApplication].keyWindow addSubview:self.popopview];
    
    WS(weakSelf);
    if ([CommonUserInfo sharedInstance].isLogin) {
        NSString *string = [NSString stringWithFormat:@"{\"user_id\" : \"%@\"}",[RSA encryptString:[CommonUserInfo sharedInstance].user_id publicKey:PublicKey]];
        [PPNetworkHelper POST:@"welfare/browse/index" parameters:@{@"json":string} success:^(id responseObject) {
            if ([responseObject[@"code"] intValue] == 1) {
                [weakSelf.popopview loadWithHtml:responseObject[@"data"][@"jiangli"]];
                weakSelf.popopview.hidden = NO;
                AudioServicesPlaySystemSound(kSystemSoundID_Vibrate);
                AudioServicesPlaySystemSound(self->scoreClickBtnID);
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.01 * NSEC_PER_SEC)), dispatch_get_main_queue(),^{
                    [weakSelf.popopview removeFromSuperview];
                    
                        ShopDetailController *vc = [[ShopDetailController alloc] init];
                        vc.model = self.dataArray[indexPath.item];
                        [self.navigationController pushViewController:vc animated:YES];
//                    shouldPrevent = NO;
                });
            } else {
                
                    ShopDetailController *vc = [[ShopDetailController alloc] init];
                    vc.model = self.dataArray[indexPath.item];
                    [self.navigationController pushViewController:vc animated:YES];
//                    shouldPrevent = NO;
            }
            
        } failure:^(NSError *error) {
//            shouldPrevent = NO;
           
                ShopDetailController *vc = [[ShopDetailController alloc] init];
                vc.model = self.dataArray[indexPath.item];
                [self.navigationController pushViewController:vc animated:YES];
            
        }];
    } else {
//        shouldPrevent = NO;
//                    if (![[CommonAction sharedInstance] isLoginWithParentVc:self.parentVC]) {
//                return;
//            }
            ShopDetailController *vc = [[ShopDetailController alloc] init];
            vc.model = self.dataArray[indexPath.item];
            [self.navigationController pushViewController:vc animated:YES];
        
        
        
    }
//    NewHomeModel *model = self.dataArray[indexPath.row];
//    WebViewController *vc = [[WebViewController alloc] init];
//    vc.title = @"详情";
//    vc.url = [NSString stringWithFormat:@"%@%@?sid=%@&userid=%@", ebaseH5,@"bargainHeader.html", model.ID, [CommonUserInfo sharedInstance].user_id];
//    if (vc) {
//        [self.navigationController pushViewController:vc animated:YES];
//    }
}

- (void)prepareUI {
    [self.view addSubview:self.collectionView];
    WS(weakSelf)
    [self.collectionView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.left.right.mas_equalTo(weakSelf.view);
        make.bottom.mas_equalTo(weakSelf.view.mas_bottom).with.offset(-Height_NavBar);
    }];
    
}

- (NewHomeHeadView *)backView {
    
    if (_backView == nil) {
        _backView = [[NewHomeHeadView alloc] init];
        _backView.frame = CGRectMake(0, 0, WIDTH, jisuan(950) - 20);
//        [_backView addSubview:self.bgImageView];
//        [_backView addSubview:self.titleView];
        
    }
    
    return _backView;
}

- (UICollectionView *)collectionView {
    if (!_collectionView) {
        UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
        CGFloat w = (WIDTH - jisuan(20) *2 - jisuan(12)) / 2;

        CGFloat h = (IS_IPHONE_X || IS_IPHONE_Xr || IS_IPHONE_Xs || IS_IPHONE_Xs_Max) ? jisuanH(500) : (kDevice_Is_iPhone6Plus) ? jisuanH(530) : (kDevice_Is_iPhone5) ? jisuanH(530) : jisuanH(530);
        layout.itemSize = CGSizeMake(w, h);
        layout.minimumLineSpacing = jisuan(12);
        layout.minimumInteritemSpacing = jisuan(12);

        layout.headerReferenceSize = CGSizeMake(WIDTH, jisuan(950) - 20);

        _collectionView = [[UICollectionView alloc] initWithFrame:CGRectZero collectionViewLayout:layout];
        _collectionView.delegate = self;
        _collectionView.dataSource = self;
        _collectionView.showsVerticalScrollIndicator = NO;
        _collectionView.showsHorizontalScrollIndicator = NO;
        _collectionView.backgroundColor = [UIColor colorWithHexString:@"F6F8FA"];
        /*!
         *  @brief  注册cell
         */
        [_collectionView registerClass:[NewHomeCollectionViewCell class] forCellWithReuseIdentifier:@"NewHomeCollectionViewCell"];

        [_collectionView registerClass:[UICollectionReusableView class]  forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"NewHomeViewControllerHeadID"];

        [_collectionView registerClass:[BottomGoodsCollectionViewCell class] forCellWithReuseIdentifier:bottomGoodsCellID];
        MJRefreshAutoNormalFooter *footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreData)];
        // 设置字体
        footer.stateLabel.font = [UIFont systemFontOfSize:17];

        // 设置颜色
        footer.stateLabel.textColor = LightGrayColor;


        // 设置文字
        [footer setTitle:@"" forState:MJRefreshStateIdle];
        [footer setTitle:@"正在加载..." forState:MJRefreshStateRefreshing];
        [footer setTitle:@"已经到底了" forState:MJRefreshStateNoMoreData];

        // 设置字体
        footer.stateLabel.font = [UIFont systemFontOfSize:17];

        // 设置颜色
        footer.stateLabel.textColor = LightGrayColor;

        // 设置footer
        _collectionView.mj_footer = footer;
        _collectionView.mj_footer.automaticallyHidden = YES;
    }
    return _collectionView;
}
- (NSMutableArray *)dataArray {
    if (!_dataArray) {
        _dataArray = [NSMutableArray array];
    }
    return _dataArray;
}
- (void)viewWillAppear:(BOOL)animated {
    
    [super viewWillAppear:animated];
    self.navigationController.navigationBar.hidden = YES;
}


@end
